package it.aekidna.cleverplatypus.workflow
{
	
	import mx.collections.ArrayCollection;
	import mx.events.PropertyChangeEvent;
	import mx.events.PropertyChangeEventKind;

   [DefaultProperty("tasks")]
	public class RepeaterWorkflow extends Workflow
	{
		[Bindable]
		public var dataProvider : ArrayCollection;
		
		[Bindable]
		public var currentData : *;
		
		private var _currentDataIndex : int = -1;
		
		private var _declaredTasks : Array;

		[Bindable]
		public function get currentDataIndex() : int
		{
			return _currentDataIndex;
		}
		
		public function set currentDataIndex( inIndex : int ) : void
		{
			//EMPTY SETTER. NEEDED TO ALLOW BINDING
		}
		
		override public function set tasks( inTasks : Array ) : void
		{
			_declaredTasks = inTasks;
		}
		
		override public function begin() : void
		{
			if( dataProvider != null && dataProvider.length > 0 )
			{
				produceTasks();
			}
			super.begin();
		}
		
		private function produceTasks() : void
		{
			_currentDataIndex ++;
			currentData = dataProvider.getItemAt( _currentDataIndex );
			dispatchEvent( 
				new PropertyChangeEvent( 
					PropertyChangeEvent.PROPERTY_CHANGE,
					false,
					false,
					PropertyChangeEventKind.UPDATE,
					"currentDataIndex",
					_currentDataIndex - 1,
					_currentDataIndex,
					this ) );
			_tasks = [];
			for each( var task : IWorkflowTask in _declaredTasks )
			{
				_tasks.push( task );
			}
		}
					
		override protected function onSubtaskCompleted( inEvent : WorkflowEvent ) : void
		{
            _processedTasks.splice( _processedTasks.indexOf( inEvent.target ), 1 );
            removeEventListeners( inEvent.target as IWorkflowTask );
            if( _flow == SERIAL && _nextTaskIndex < _tasks.length )
            {
                runNextTask();
                return;
            }
            else
            {
                if( _processedTasks.length == 0 )
                {
                	if( _currentDataIndex == dataProvider.length -1 )
                	{
	                    Workflow.LOGGER.debug(
	                        "Task '{0}' completed", name );
	                    dispatchEvent( new WorkflowEvent( WorkflowEvent.COMPLETED ) );
	                }
	                else
	                {
	                	produceTasks();
	                	_nextTaskIndex = 0;
	                	_processedTasks = [];
	                	runNextTask();
	                }
                }
            }
			
		}
	}
}